package com.mnt.washio.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.mnt.washio.R;
import com.mnt.washio.adapters.MenuListAdapter;
import com.mnt.washio.objects.Address;
import com.mnt.washio.objects.OrderObject;
import com.mnt.washio.utils.SessionManager;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;
import com.mnt.washio.utils.network.ws.BaseWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl.WebServiceFlag;
import com.mnt.washio.utils.network.ws.GetAddressListWSControl;
import com.mnt.washio.utils.network.ws.GetCurrentOrderWSControl;
import com.parse.ParseUser;

public class MainActivity extends Activity implements
		WebServiceCommunicatorListener {

	private String[] mMenuIcons, mMenuTexts;
	private ListView mListView;
	private MenuListAdapter mAdapter;
	private CountDownTimer cDT;
	private boolean ready = false;
	private ProgressDialog pd;
	private boolean okAddress = false, okOrder = false, isPricingTab;
	private Object curData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		overridePendingTransition(R.anim.slide_in_from_left, R.anim.anim_alpha);

		initView();
		initProperties();
		initListeners();
		ParseUser.getCurrentUser().fetchInBackground(null);
	}

	private void initView() {
		mMenuIcons = getResources().getStringArray(R.array.menu_icons);
		mMenuTexts = getResources().getStringArray(R.array.menu_texts);
		mListView = (ListView) findViewById(R.id.list_menus);
		mAdapter = new MenuListAdapter(this, mMenuIcons, mMenuTexts,
				R.layout.item_list_menu);
		mListView.setAdapter(mAdapter);

		cDT = new CountDownTimer(3000, 3000) {

			@Override
			public void onTick(long arg0) {
			}

			@Override
			public void onFinish() {
				ready = false;
			}
		};

	}

	private void initProperties() {
		pd = new ProgressDialog(this);
		pd.setCancelable(false);
	}

	private void initListeners() {
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				if (!Statics.isNetworkConnected(getBaseContext())) {
					new AlertDialog.Builder(MainActivity.this)
							.setTitle("Notice")
							.setMessage("Oops! No internet connection.")
							.setPositiveButton("Ok",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub

										}
									}).show();
				} else {
					goToDetailPage(pos);
				}
			}
		});
	}

	private void goToDetailPage(int pos) {
		isPricingTab = false;
		Intent i = null;
		String userObjectId = ParseUser.getCurrentUser().getObjectId();
		if (userObjectId != null) {
			switch (pos) {
			case 0:

				okAddress = false;
				okOrder = false;

				new GetAddressListWSControl(this, this, userObjectId).execute();
				new GetCurrentOrderWSControl(this, this, userObjectId)
						.execute();
				break;

			case 1:
				i = new Intent(this, ShareActivity.class);
				i.putExtra("TITLE", "Share Washio");
				break;

			case 2:
				i = new Intent(this, MyAccountActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 3:
				i = new Intent(this, PaymentActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 4:
				i = new Intent(this, AddressActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 5:
				isPricingTab = true;
				if (SessionManager.getSessionManager(this).getOurArrayAddress()
						.size() == 0) {
					okOrder = true;
					okAddress = false;
					new GetAddressListWSControl(this, this, userObjectId)
							.execute();
				} else {
					i = new Intent(this, PricingActivity.class);
					i.putExtra("TITLE", mMenuTexts[pos]);
					i.putExtra("ZIPCODE", SessionManager
							.getSessionManager(this).getOurArrayAddress()
							.get(0).getZipCode());
				}
				break;

			case 6:
				i = new Intent(this, HelpActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			}
		} else {
			i = new Intent(this, LoginActivity.class);
			i.putExtra("TITLE", "Login");
		}

		if (i != null) {
			startActivity(i);
		}
	}

	@Override
	public void onBackPressed() {
		if (ready) {
			super.onBackPressed();
		} else {
			ready = true;
			Statics.showToast(this, "Press back again to exit");
			cDT.start();
		}
	}

	@Override
	protected void onDestroy() {
		SessionManager.destroySession();
		super.onDestroy();
	}

	@Override
	public void onConnectionOpen(BaseWSControl wsControl, WebServiceFlag flag) {
		// TODO Auto-generated method stub
		if (!pd.isShowing()) {
			pd.setMessage("Loading...");
			pd.show();
		}
	}

	@Override
	public void onConnectionError(BaseWSControl wsControl, WebServiceFlag flag,
			String error) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Error.", Toast.LENGTH_SHORT).show();
		pd.dismiss();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onConnectionDone(BaseWSControl wsControl, WebServiceFlag flag,
			Object result) {
		// TODO Auto-generated method stub
		if (flag == WebServiceFlag.GET_ADDRESS) {

			ArrayList<Address> arrayAddress = (ArrayList<Address>) result;
			if (arrayAddress.size() > 0) {
				okAddress = true;
				SessionManager.getSessionManager(this).setOurArrayAddress(
						arrayAddress);

				if (isPricingTab) {
					Intent i = new Intent(this, PricingActivity.class);
					i.putExtra("TITLE", mMenuTexts[5]);
					i.putExtra("ZIPCODE", arrayAddress.get(0).getZipCode());
					startActivity(i);
				}
			} else {
				Statics.showToast(this, "Address is required!");
				Intent i = new Intent(MainActivity.this,
						RegisterStep2Activity.class);
				startActivityForResult(i, 123);
			}

		} else if (flag == WebServiceFlag.ORDER_CURRENT) {
			okOrder = true;
			curData = result;
		}

		checkContition();
	}

	private void checkContition() {
		if (okAddress && okOrder) {
			if (pd.isShowing())
				pd.dismiss();

			if (!isPricingTab) {
				checkOrder((OrderObject) curData);
			}

		}
	}

	@Override
	public void onUpdateData(BaseWSControl wsControl, WebServiceFlag flag,
			Object data) {
		// TODO Auto-generated method stub

	}

	public void checkOrder(OrderObject order) {

		if (null == order || !order.getRating().equals("null")
				|| order.getStatusLookup().equals("ORDER_CANCELLED")) {
			Intent i = new Intent(this, OrderActivity.class);
			i.putExtra("TITLE", mMenuTexts[0]);
			startActivity(i);
			return;
		}

		if (order.getStatusLookup().equals("ORDER_DELIVERED")
				|| order.getStatusLookup().equals("CUSTOMER_REFUNDED")
				|| order.getStatusLookup().equals("CUSTOMER_BILLED")) {
			Intent i = new Intent(this, OrderComplete.class);
			i.putExtra("ORDER_OBJECT", order);
			startActivity(i);
			return;
		}

		Intent i = new Intent(this, OrderStatusActivity.class);
		i.putExtra("TITLE", "Order Status");
		i.putExtra("ORDER_OBJECT", order);
		startActivity(i);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			new GetAddressListWSControl(this, this, ParseUser.getCurrentUser()
					.getObjectId()).execute();
		} else {
			okAddress = false;
			// dismiss dialog.
			if (pd.isShowing())
				pd.dismiss();
			return;
		}

		checkContition();
	}

}
